package com.jsb.laundry.controller;

import com.alibaba.fastjson.JSONObject;
import com.jsb.laundry.common.enums.ReturnStatusCode;
import com.jsb.laundry.common.response.WebResponse;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.redis.RedisUtil;
import com.jsb.laundry.dao.CouponDao;
import com.jsb.laundry.model.dto.CouponRecordDto;
import com.jsb.laundry.model.dto.MonthCardDto;
import com.jsb.laundry.model.entity.CouponUserBag;
import com.jsb.laundry.model.vo.PrePayVo;
import com.jsb.laundry.service.CouponService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = {"优惠券(vip)服务"})
@RestController
@RequestMapping("/coupon")
public class CouponController {
    private static final Logger LOGGER = LoggerFactory.getLogger(CouponController.class);

    @Resource
    private CouponDao couponDao;

    @Resource
    private CouponService couponService;
    @Resource
    private RedisUtil redisUtil;

    /**
     * vip购买是数据保存
     *
     * @param couponUserBag
     * @return
     */
    @PostMapping("/vipDataSave")
    public WebResponse vipDataSave(@RequestBody CouponUserBag couponUserBag) {
        if (JSBUtil.isEmptyString(couponUserBag.getUserId()) || JSBUtil.isEmptyString(couponUserBag.getTcId())) {
            return WebResponse.failOfParameter();
        }
        PrePayVo returnMsg = couponService.vipDataSave(couponUserBag);
        return WebResponse.successData(returnMsg);
    }


    /**
     * 会员中心页面获取优惠券套餐
     */
    @PostMapping("/vipCenterPage")
    public WebResponse vipCenterPage() {
        LOGGER.info("用户：{},会员中心页面获取优惠券套餐");
        List<CouponRecordDto> returnMsg = couponDao.vipCenterPage();
        return WebResponse.successData(returnMsg);
    }

    /**
     * 用户优惠券列表(userId、useType(0:未使用_当月,1:已使用_当月,2:待领取,3:待发放))
     */
    @ApiOperation(value = "用户优惠券列表", notes = "用户优惠券列表", httpMethod = "POST")
    @PostMapping("/getCouponListByUserId")
    public WebResponse getCouponListByUserId(@RequestBody CouponUserBag couponRecord) {
        LOGGER.info("用户获取的优惠券列表：{}", couponRecord);
        if (JSBUtil.isEmptyString(couponRecord.getUserId()) || JSBUtil.isEmptyString(couponRecord.getUseType())) {
            return WebResponse.failOfParameter();
        }

//        PageHelper.startPage(couponRecord.getPageNum(), couponRecord.getPageSize());

        Object currentMonthCoupon = couponService.getCouponListByUserId(couponRecord.getUserId(), couponRecord.getUseType(), couponRecord.getCurrentNumber());
        return WebResponse.successData(currentMonthCoupon);
    }

    /**
     * 获取当前可用的优惠券列表(userId、useType(0:未使用,1:已使用))
     */
    @PostMapping("/getAvailableCoupon")
    public WebResponse getAvailableCoupon(@RequestBody CouponUserBag couponRecord) {
        LOGGER.info("获取当前可用的优惠券列表：{}", couponRecord);
        if (JSBUtil.isEmptyString(couponRecord.getUserId()) || JSBUtil.isEmptyString(couponRecord.getUseType())) {
            return WebResponse.failOfParameter();
        }
        List<CouponUserBag> currentMonthCoupon = couponDao.findCurrentMonthCoupon(couponRecord.getUserId(), couponRecord.getUseType(), new Date());
        return WebResponse.successData(currentMonthCoupon);
    }


    /**
     * 获取当前用户的我的页面的账户余额、卡券数量(userId)
     */
    @PostMapping("/getUserBalanceAndCoupon")
    public WebResponse getUserBalanceAndCoupon(@RequestBody CouponUserBag couponRecord) {
        if (JSBUtil.isEmptyString(couponRecord.getUserId())) {
            return WebResponse.failOfParameter();
        }
        Map<String, String> returnMsg = couponDao.getUserBalanceAndCoupon(couponRecord.getUserId());
        String yhq = couponDao.findByC(couponRecord.getUserId());
        returnMsg.put("remainingCouponAmount", String.valueOf(Integer.parseInt(yhq) / 100));
        return WebResponse.successData(returnMsg);
    }


    /**
     * 获取用户账户余额页面(userId)
     */
    @PostMapping("/accountBalancePage")
    public WebResponse accountBalancePage(@RequestBody CouponUserBag couponRecord) {
        LOGGER.info("获取用户账户余额页面：{}", couponRecord);
        if (JSBUtil.isEmptyString(couponRecord.getUserId())) {
            HashMap map = new HashMap<>();
            map.put("userBalance", "0");
            map.put("userOtherBalance", "0");
            map.put("total", "0");
            return WebResponse.successData(map);
        }
        //业务处理
        HashMap returnMsg = couponDao.accountBalancePage(couponRecord.getUserId());

        //返回数据
        return WebResponse.successData(returnMsg);
    }

    /**
     * 获取是否购买了优惠券（userId）
     *
     * @param couponRecord
     * @return
     */
    @PostMapping("/getUserCouponBuyEffective")
    public WebResponse getUserCouponBuyEffective(@RequestBody CouponUserBag couponRecord) {
        LOGGER.info("获取是否购买了优惠券：{}", couponRecord);
        if (JSBUtil.isEmptyString(couponRecord.getUserId())) {
            return WebResponse.successData(0);
//            return WebResponse.success(ReturnCode.NOT_FOUND_COUPON.getCode(), ReturnCode.NOT_FOUND_COUPON.getMsg());
        }
        //业务处理
        int var0 = couponDao.getUserCouponBuyEffective(couponRecord.getUserId());
        //返回数据
        return WebResponse.successData(var0);
    }

    /**
     * 洗衣卡券列表(userId,status)
     *
     * @param data
     * @return
     */
    @ApiOperation(value = "洗衣卡券列表", notes = "洗衣卡券列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", required = true, paramType = "body", dataType = "String"),
            @ApiImplicitParam(name = "pageSize", value = "当前页大小", required = true, paramType = "body", dataType = "String"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "body", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "使用状态(0:未使用，1:已使用,2:已过期 )", required = true, paramType = "body", dataType = "String"),
    })
    @PostMapping("/monthCardList")
    public WebResponse monthCardList(@RequestBody MonthCardDto data) {
        LOGGER.info("洗衣卡券列表查看:{}", data);

        String status = data.getStatus();//使用状态
        String userId = data.getParam();//userId

        if (JSBUtil.isEmptyString(userId) || JSBUtil.isEmptyString(status)) {
            return WebResponse.failOfParameter();
        }

//        PageHelper.startPage(data.getPageNumber(), data.getPageSize());
        List<HashMap> res = couponDao.monthCardList(userId, status);
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("list", res);
        return WebResponse.successData(objectObjectHashMap);
    }

    @ApiOperation(value = "用户领取平安券", notes = "用户领取平安券", httpMethod = "POST")
    @PostMapping("collectPingAnVoucher")
    @Transactional
    public synchronized WebResponse collectPingAnVoucher(@RequestBody JSONObject object) {
        String userId = object.getString("userId");
        String phone = object.getString("phone");
        //findByUserPhone
        String userPhone = couponDao.findByUserPhone(userId);
        if (JSBUtil.isEmptyString(userPhone)){
            return WebResponse.failOfParameter();
        }
        int len = userPhone.length();
        String substring = userPhone.substring(len - 4);
        if (!phone.equals(substring)) {
            return WebResponse.success(ReturnStatusCode.THE_PHONE_NUMBER_IS_INCONSISTENT.getCode(),ReturnStatusCode.THE_PHONE_NUMBER_IS_INCONSISTENT.getMsg());
        }
        //findByUserPhone
        userPhone = couponDao.findByUserPhone(userId);
        if (JSBUtil.isEmptyString(userPhone)){
            return WebResponse.failOfParameter();
        }
        //查询优惠券是否领取过
        int findByCoupon = couponDao.findByCoupon(userId);
        if (findByCoupon==1){
            return WebResponse.success(ReturnStatusCode.RECEIVED_THE_COUPON.getCode(),ReturnStatusCode.RECEIVED_THE_COUPON.getMsg());
        }


        if (phone.equals(substring)) {
            //领取优惠券
            String payId = "pa"+JSBUtil.generateLongOrderNO();
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime oneMonthLater = now.plusMonths(1);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String currentDateTime = now.format(formatter);//当前日期时间
            String oneMonthLaterDateTime = oneMonthLater.format(formatter);//一个月后日期时间
            int addcouponUserBag= couponDao.addcouponUserBag(userId,payId,currentDateTime,oneMonthLaterDateTime);
            return WebResponse.successData(addcouponUserBag);
        }else {
            return WebResponse.success(ReturnStatusCode.THE_PHONE_NUMBER_IS_INCONSISTENT.getCode(),ReturnStatusCode.THE_PHONE_NUMBER_IS_INCONSISTENT.getMsg());

        }

    }



}
